﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Model;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.LinqBuilder;
using Furion.UnifyResult;
using Masuit.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 报修工单接口
    /// </summary>
    [DynamicApiController]
    public class NrWorkOrderController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public NrWorkOrderController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// PC端-安卓端-工单列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <param name="content"></param>
        /// <param name="created"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] long epid, [FromForm] string content, [FromForm] DateTime created)
        {
            List<NrWorkOrder> db_NrWorkOrders = await db.Queryable<NrWorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "待接单")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(created != DateTime.MinValue, wo => SqlFunc.DateIsSame(wo.Created, created, DateType.Day))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToListAsync();

            List<NrWorkOrder> wks_NrWorkOrders = await db.Queryable<NrWorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "未开始")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(created != DateTime.MinValue, wo => SqlFunc.DateIsSame(wo.Created, created, DateType.Day))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToListAsync();

            List<NrWorkOrder> jxz_NrWorkOrders = await db.Queryable<NrWorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "进行中")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToListAsync();

            List<NrWorkOrder> ywc_NrWorkOrders = await db.Queryable<NrWorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "已完成")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToListAsync();

            JObject data = new();
            data.Add("daiban", db_NrWorkOrders == null ? null : JArray.FromObject(db_NrWorkOrders));
            data.Add("weikaishi", wks_NrWorkOrders == null ? null : JArray.FromObject(wks_NrWorkOrders));
            data.Add("jinxingzhong", jxz_NrWorkOrders == null ? null : JArray.FromObject(jxz_NrWorkOrders));
            data.Add("yiwancheng", ywc_NrWorkOrders == null ? null : JArray.FromObject(ywc_NrWorkOrders));

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-工单列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="begintime"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostAlist([FromForm] long eid, [FromForm] long epid, [FromForm] string content, [FromForm] string type, [FromForm] DateTime begintime, [FromForm] string status, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {

            RefAsync<int> total = 0;
            List<NrWorkOrder> NrWorkOrders = await db.Queryable<NrWorkOrder>()
                .Mapper(async wo => {
                    if (!string.IsNullOrEmpty(wo.Epids)) {
                        List<string> realnames = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{wo.Epids}')").Select(ep => ep.Realname).ToListAsync();
                        wo.EpRealnames = string.Join(",", realnames.ToArray());
                    }
                })
                .Where(wo => wo.Eid == eid)
                .WhereIF(!string.IsNullOrEmpty(status), wo => wo.Status == status)
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(begintime != DateTime.MinValue, wo => wo.BeginTime.Date == begintime.Date)
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, total);

            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = NrWorkOrders,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 眼镜端-工单列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="begintime"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostVrlist([FromForm] long eid, [FromForm] long epid, [FromForm] string content, [FromForm] string type, [FromForm] DateTime begintime, [FromForm] string status, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {

            RefAsync<int> total = 0;
            List<NrWorkOrder> NrWorkOrders = await db.Queryable<NrWorkOrder>()
                .Mapper(async wo => {
                    if (!string.IsNullOrEmpty(wo.Epids))
                    {
                        List<string> realnames = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{wo.Epids}')").Select(ep => ep.Realname).ToListAsync();
                        wo.EpRealnames = string.Join(",", realnames.ToArray());
                    }
                })
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status != "已完成")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(begintime != DateTime.MinValue, wo => wo.BeginTime.Date == begintime.Date)
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, total);

            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = NrWorkOrders,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id)
        {
            await db.Deleteable<NrWorkOrder>().Where(wo => wo.Eid == eid && wo.Id == id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="NrWorkOrder"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] NrWorkOrder NrWorkOrder)
        {
            await db.Updateable<NrWorkOrder>(NrWorkOrder).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端-查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            NrWorkOrder NrWorkOrder = await db.Queryable<NrWorkOrder>().Where(wo => wo.Eid == eid && wo.Id == id).SingleAsync();
            
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = NrWorkOrder,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端-派单
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="pdlx"></param>
        /// <param name="epids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostPaidan([FromForm] long eid, [FromForm] long woid, [FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] string manhour, [FromForm] string pdlx, [FromForm] long[] epids)
        {
            if (pdlx.Equals("部门"))
            {
                List<long> epidslist = await db.Queryable<Employee>().Where(ep => ep.DefaultEid == eid && ep.Dpid == epids.First()).Select(ep => ep.Id).ToListAsync();
                await db.Updateable<NrWorkOrder>(new NrWorkOrder { Epids = string.Join(",", epidslist), BeginTime = begintime, EndTime = endtime, ManHour = manhour, Status = "未开始" })
                    .UpdateColumns(wo => new { wo.Epids, wo.BeginTime, wo.EndTime, wo.ManHour, wo.Status })
                    .Where(wo => wo.Id == woid && wo.Eid == eid)
                    .ExecuteCommandAsync();
            }
            else
            {
                await db.Updateable<NrWorkOrder>(new NrWorkOrder { Epids = string.Join(",", epids), BeginTime = begintime, EndTime = endtime, ManHour = manhour, Status = "未开始" })
                    .UpdateColumns(wo => new { wo.Epids, wo.BeginTime, wo.EndTime, wo.ManHour, wo.Status })
                    .Where(wo => wo.Id == woid && wo.Eid == eid)
                    .ExecuteCommandAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-新派单接口
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="begintime"></param>
        /// <param name="endtime"></param>
        /// <param name="manhour"></param>
        /// <param name="pdlx"></param>
        /// <param name="epids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostApaidan([FromForm] long eid, [FromForm] long woid, [FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] string manhour, [FromForm] string pdlx, [FromForm] string epids)
        {
            if (pdlx.Equals("部门"))
            {
                List<long> epidslist = await db.Queryable<Employee>().Where(ep => ep.DefaultEid == eid && ep.Dpid == epids.First()).Select(ep => ep.Id).ToListAsync();
                await db.Updateable<NrWorkOrder>(new NrWorkOrder { Epids = string.Join(",", epids), BeginTime = begintime, EndTime = endtime, ManHour = manhour, Status = "未开始" })
                    .UpdateColumns(wo => new { wo.Epids, wo.BeginTime, wo.EndTime, wo.ManHour, wo.Status })
                    .Where(wo => wo.Id == woid && wo.Eid == eid)
                    .ExecuteCommandAsync();
            }
            else
            {
                await db.Updateable<NrWorkOrder>(new NrWorkOrder { Epids = string.Join(",", epids), BeginTime = begintime, EndTime = endtime, ManHour = manhour, Status = "未开始" })
                .UpdateColumns(wo => new { wo.Epids, wo.BeginTime, wo.EndTime, wo.ManHour, wo.Status })
                    .Where(wo => wo.Id == woid && wo.Eid == eid)
                    .ExecuteCommandAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-接单
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="begintime"></param>
        /// <param name="endtime"></param>
        /// <param name="manhour"></param>
        /// <param name="epids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostJiedan([FromForm] long eid, [FromForm] long woid, [FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] string manhour, [FromForm] long[] epids)
        {
            await db.Updateable<NrWorkOrder>(new NrWorkOrder { Epids = string.Join(",", epids), BeginTime = begintime, EndTime = endtime, ManHour = manhour, Status = "未开始" })
                .UpdateColumns(wo => new { wo.Epids, wo.BeginTime, wo.EndTime, wo.ManHour, wo.Status })
                .Where(wo => wo.Id == woid && wo.Eid == eid)
                .ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }



        /// <summary>
        /// 安卓端-我的-今日完成
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostJinriwancheng([FromForm] long eid, [FromForm] long epid)
        {
            int jrwc_total = await db.Queryable<NrWorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where($"FIND_IN_SET({epid}, epids)")
                .Where(wo => wo.Status == "已完成")
                .Where(wo => wo.SjEndTime.Date == DateTime.Now.Date)
                .CountAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = jrwc_total,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-首页-待办计划
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDaibanjihua([FromForm] long eid, [FromForm] long epid)
        {
            int dbjh_total = await db.Queryable<NrWorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where($"FIND_IN_SET({epid}, epids)")
                .Where(wo => wo.Status == "未开始")
                .CountAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = dbjh_total,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-首页-待办维修
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDaibanweixiu([FromForm] long eid, [FromForm] long epid)
        {
            int dbwx_total = await db.Queryable<NrWorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where($"FIND_IN_SET('{epid}', epids)")
                .Where(wo => wo.Status == "未开始")
                .CountAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = dbwx_total,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 获取指派人
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetzhipairen([FromForm] long eid, [FromForm] long woid)
        {
            List<Employee> employees = new();
            string epids = await db.Queryable<NrWorkOrder>().Where(wo => wo.Eid == eid && wo.Id == woid).Select(wo => wo.Epids).SingleAsync();
            if (!string.IsNullOrEmpty(epids))
            {
                employees = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{epids}')").ToListAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = employees,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-更新工单状态
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdatestatus([FromForm] long eid, [FromForm] long woid, [FromForm] string status)
        {
            await db.Updateable<NrWorkOrder>(new NrWorkOrder { Status = status })
                .UpdateColumns(wo => new { wo.Status })
                .Where(wo => wo.Eid == eid && wo.Id == woid)
                .ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
